package com.common.supply.Utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.util.Arrays;

/**
 * @Author: Jamnsin
 * @Date: 2021/9/5 1:46 下午
 */
@Slf4j
public class OnepipeTripleDES {

    // If it's bank.account , it should be: TripleDES.encrypt("{accountNumber};{bankCBNCode}",secretKey)
    public static String encrypt(String toBeEncrypted, String key) {

        try {
            MessageDigest md = MessageDigest.getInstance("md5");
            byte[] digestOfPassword = md.digest(key.getBytes("UTF-16LE"));
            byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);

            for (int j = 0, k = 16; j < 8; ) {
                keyBytes[k++] = keyBytes[j++];
            }

            SecretKey secretKey = new SecretKeySpec(keyBytes, 0, 24, "DESede");
            IvParameterSpec iv = new IvParameterSpec(new byte[8]);

            Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);

            byte[] plainTextBytes = toBeEncrypted.getBytes("UTF-16LE");
            byte[] cipherText = cipher.doFinal(plainTextBytes);

            return new String(Base64.encodeBase64(cipherText));
        } catch (Exception e) {
            log.error("OnepipeTripleDES 加密异常，toBeEncrypted = {}", toBeEncrypted, e);
            return null;
        }
    }

}
